package com.liu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.common.CustomException;
import com.liu.entity.Category;
import com.liu.entity.Dish;
import com.liu.entity.Setmeal;
import com.liu.mapper.CategoryMapper;
import com.liu.service.CategoryService;
import com.liu.service.DishService;
import com.liu.service.SetmealService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private DishService dishService;

    @Resource
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {

        //创建条件构造器对象
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id查询对应的菜品
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);

        //调用DishService的count方法查询符合条件的菜品数量
        long dishCount = dishService.count(dishLambdaQueryWrapper);

        //如果当前分类关联菜品，抛出异常
        if (dishCount > 0) {
            throw new CustomException("当前分类下关联了菜品，无法删除");
        }

        //创建条件构造器对象
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id查询对应的套餐
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);

        //调用SetmealService的count方法查询符合条件的套餐数量
        long setmealCount = setmealService.count(setmealLambdaQueryWrapper);

        //如果当前分类关联套餐，抛出异常
        if (setmealCount > 0) {
            throw new CustomException("当前分类下关联了套餐，无法删除");
        }

        //删除分类
        super.removeById(id);

    }
}
